﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI;

namespace iGRID_Ooredoo_SPCRM_My_Opportunities.Layouts.iGRID_Ooredoo_SPCRM_My_Opportunities
{
    public partial class Account_Master : LayoutsPageBase
    {

        public static string AccLstName { get; set; }
        public string ErrorMsgs { get; set; }
        ExceptionHandler exHandler = new ExceptionHandler();
        public string camlQry { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {
            tblAddItems.Visible = false;
            AccLstName = "Customers Master";
            lblError.Text = "";
            lblError.Visible = false;
            BindNullValues();
        }

        protected void btnGetAcc_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtAccName.Text))
            {
                hdnSessionAccName.Text = "";
                btnProceed.Enabled = false;
                BindData();
            }
            else
            {
                gvAcc.DataSource = null;
                gvAcc.DataBind();
                hdnSessionAccName.Text = "";
                //lblError.Visible = true;
                //lblError.Text = "Please enter the value to find";
                BindNullValues();
            }
        }

        protected void btnClose_Click(object sender, EventArgs e)
        {
            Session["AccountName"] = "";
            Response.Write("<script language='javascript'>parent.window.location.href = parent.window.location.href</script>");
        }


        protected override void Render(HtmlTextWriter writer)
        {
            const string onMouseOverStyle = "this.className='GridViewMouseOver';";
            const string onMouseOutStyle = "this.className='{0}';";

            foreach (GridViewRow gvr in gvAcc.Rows)
            {
                gvr.Attributes["onmouseover"] = onMouseOverStyle;
                gvr.Attributes.Add("onmouseover", "this.style.cursor='pointer'");
                gvr.Attributes["onmouseout"] = String.Format(
                        onMouseOutStyle,
                        this.GetRowStyleCssClass(gvr.RowState));
                gvr.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(
                        gvAcc,
                        String.Concat("Select$", gvr.RowIndex),
                        true);
            }

            base.Render(writer);
        }


        private string GetRowStyleCssClass(DataControlRowState state)
        {
            if ((state & DataControlRowState.Edit) > 0)
            {
                return gvAcc.EditRowStyle.CssClass;
            }
            else if ((state & DataControlRowState.Selected) > 0)
            {
                return gvAcc.SelectedRowStyle.CssClass;
            }
            else if ((state & DataControlRowState.Alternate) > 0)
            {
                return gvAcc.AlternatingRowStyle.CssClass;
            }
            else
            {
                return gvAcc.RowStyle.CssClass;
            }
        }


        private void BindData()
        {
            SPQuery qry = new SPQuery();
            string camlQry = "";
            using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    SPList oList = oWeb.Lists.TryGetList(AccLstName);
                    if (oList != null)
                    {
                        camlQry = "<Where><BeginsWith><FieldRef Name=\"Title\" /><Value Type=\"Text\">" + Convert.ToString(txtAccName.Text).Trim() + "</Value></BeginsWith></Where>";
                        qry.Query = camlQry;
                        SPListItemCollection oLstItem = oList.GetItems(qry);
                        if (oLstItem.Count > 0)
                        {
                            gvAcc.DataSource = oLstItem.GetDataTable();
                            gvAcc.DataBind();
                        }
                        else
                        {
                            gvAcc.DataSource = null;
                            gvAcc.DataBind();
                            hdnSessionAccName.Text = "";
                        }
                    }
                }
            }
            BindNullValues();
        }

        protected void btnNewItems_Click(object sender, EventArgs e)
        {
            tblAddItems.Visible = true;
            gvAcc.Visible = false;
            txtAccName.Text = "";
            hdnSessionAccName.Text = "";
            btnProceed.Enabled = false;
        }



        protected void btnRecSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {

                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        SPListItem oLstItems = null;
                        SPListItemCollection oLstItemcolls = null;
                        SPListItem oLstItemcoll = null;

                        using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
                        {
                            using (SPWeb oWeb = oSite.OpenWeb())
                            {
                                oWeb.AllowUnsafeUpdates = true;
                                SPList oList = oWeb.Lists.TryGetList(AccLstName);
                                if (oList != null)
                                {
                                    SPQuery qry = new SPQuery();
                                    camlQry = "<Where><Eq><FieldRef Name=\"Customer_x0020_ID\" /><Value Type=\"Text\">" + Convert.ToString(txtCustomerID.Text).Trim() + "</Value></Eq></Where>";
                                    qry.Query = camlQry;
                                    oLstItemcolls = oList.GetItems(qry);

                                    if (oLstItemcolls.Count == 0)
                                    {
                                        oLstItemcoll = oList.Items.Add();
                                        oLstItemcoll["Title"] = txtCustomer.Text;
                                        oLstItemcoll["Customer_x0020_ID"] = txtCustomerID.Text;
                                        oLstItemcoll["Phone"] = txtPhone.Text;
                                        oLstItemcoll["Email_x0020_ID"] = txtMailID.Text;
                                        oLstItemcoll["Website"] = txtWebsite.Text;
                                        oLstItemcoll.Update();
                                        tblAddItems.Visible = false;
                                        txtAccName.Text = txtCustomer.Text;
                                        BindData();
                                        ClearControls();
                                        lblError.Visible = false;
                                    }
                                    else
                                    {
                                        lblError.Visible = true;
                                        lblError.Text = "Duplication customer ID not allowed";
                                    }

                                }
                                oWeb.AllowUnsafeUpdates = false;
                            }
                        }
                    });
                }
                catch (Exception ex)
                {
                    ErrorMsgs = "iGRID_Ooredoo_SPCRM_Opportunity_Forms" + " :: " + "AccountMaster" + " :: " + "btnRecSave_Click";
                    exHandler.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                }
            }
        }


        private void ClearControls()
        {
            txtCustomer.Text = ""; txtCustomerID.Text = ""; txtPhone.Text = ""; txtMailID.Text = ""; txtWebsite.Text = "";
        }

        protected void btnRecCancel_Click(object sender, EventArgs e)
        {
            ClearControls();
            tblAddItems.Visible = false;
        }

        private void BindNullValues()
        {
            if (gvAcc.Rows.Count == 0)
            {
                #region "temp"

                DataTable dt = new DataTable();
                dt.Columns.Add("Title", typeof(string));
                dt.Columns.Add("Customer_x0020_ID", typeof(string));
                dt.Columns.Add("Phone", typeof(string));
                dt.Columns.Add("Email_x0020_ID", typeof(string));

                DataRow dr = null;

                dr = dt.NewRow();
                dr["Title"] = "Type into search box above then press 'Enter' to start your search";
                dr["Customer_x0020_ID"] = string.Empty;
                dr["Phone"] = string.Empty;
                dr["Email_x0020_ID"] = string.Empty;
                dt.Rows.Add(dr);
                gvAcc.DataSource = dt;
                gvAcc.DataBind();
                gvAcc.Rows[0].Cells[0].ColumnSpan = 4;
                gvAcc.Rows[0].Cells[1].Visible = false;
                gvAcc.Rows[0].Cells[2].Visible = false;
                gvAcc.Rows[0].Cells[3].Visible = false;

                gvAcc.Rows[0].Cells[0].Style.Add("text-align", "center");
                gvAcc.Rows[0].Cells[0].Style.Add("vertical-align", "top");
                #endregion

                //lblError.Text = "No records found";
                //gvAcc.HeaderRow.Height = 25;
                //gvAcc.Height = 230;
                //lblError.Visible = true;
            }

            else
            {
                lblError.Visible = false;
                gvAcc.Visible = true;

            }

        }

        //protected void gvAcc_OnSelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        //{
        //    GridViewRow row = gvAcc.Rows[e.NewSelectedIndex];
        //    if (row.Cells[0].Text == "QName2")
        //    {
        //        e.Cancel = true;
        //        hdnSessionAccName.Text = row.Cells[0].Text;
        //        Session["AccountName"] = hdnSessionAccName.Text;

        //    }
        //}
        protected void gvAcc_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            GridViewRow row = gvAcc.SelectedRow;
            hdnSessionAccName.Text = row.Cells[0].Text;
            //Session["AccountName"] = hdnSessionAccName.Text;
            hdnSessionAccName.Text = gvAcc.SelectedRow.Cells[0].Text;

            if (!string.IsNullOrEmpty(hdnSessionAccName.Text))

                btnProceed.Enabled = true;
            else
                btnProceed.Enabled = false;

        }


        protected void gvAcc_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                gvAcc.PageIndex = e.NewPageIndex;
                //tblEnquiryActions = GetEnquiryActionsTable();
                BindData();
            });
        }

        protected void gvAcc_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //add css to GridViewrow based on rowState     
                e.Row.CssClass = e.Row.RowState.ToString();
                //Add onclick attribute to select row.   
                e.Row.Attributes.Add("onclick", String.Format("javascript:__doPostBack('gvAcc','Select${0}')", e.Row.RowIndex));
            }
        }

    }
}

